package com.banshuibao.bsb_android.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.model.DownloadedAudioModel;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.XToast;
import com.bumptech.glide.Glide;
import com.cunoraz.gifview.library.GifView;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 显示视频ID列表的适配器
 *
 * @author CC视频
 */
public class DownloadedAudioAdapter extends BaseAdapter implements MediaPlayerUtil.MediaPlayerPlayingListener {

    public void OnViewOnClickListener(OnViewOnClickListener onViewOnClicklistener) {
        this.onViewOnClicklistener = onViewOnClicklistener;
    }

    public interface OnViewOnClickListener {
        void onClick(DownloadedAudioModel data);
    }

    private List<DownloadedAudioModel> pairs;

    private Context context;

    private boolean isShowCheck;

    private MediaPlayer media;

    private MediaPlayerUtil mediaPlayerUtil;

    private String time;

    private String playUuid;

    private OnViewOnClickListener onViewOnClicklistener;

    public DownloadedAudioAdapter(Context context) {
        this.pairs = new ArrayList<>();
        this.context = context;
        mediaPlayerUtil = new MediaPlayerUtil(context);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(this);
    }

    public void setPairs(List<DownloadedAudioModel> list) {
        if (this.pairs != null) {
            this.pairs.clear();
            this.pairs.addAll(list);
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return pairs.size();
    }

    @Override
    public DownloadedAudioModel getItem(int position) {
        return pairs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_downloaded_audio, parent, false);
            viewHolder.img = convertView.findViewById(R.id.img);
            viewHolder.name = convertView.findViewById(R.id.name);
            viewHolder.check = convertView.findViewById(R.id.check_iv);
            viewHolder.duty = convertView.findViewById(R.id.duty);
            viewHolder.recyclerView = convertView.findViewById(R.id.recyclerView);
            viewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
            viewHolder.recyclerView.setNestedScrollingEnabled(false);
            viewHolder.question = convertView.findViewById(R.id.question);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final DownloadedAudioModel data = getItem(position);
        if (data != null) {
            viewHolder.name.setText(data.getName());
            viewHolder.duty.setText(data.getDuty());
            viewHolder.question.setText(data.getQuestion());
            if (!TextUtils.isEmpty(data.getImg())) {
                byte[] bitmapArray = Base64.decode(data.getImg(), Base64.DEFAULT);
                Glide.with(context).load(bitmapArray).
                        bitmapTransform(new CropCircleTransformation(context)).into(viewHolder.img);
            } else
                viewHolder.img.setImageResource(R.drawable.login_iv);
            if (isShowCheck)
                viewHolder.check.setVisibility(View.VISIBLE);
            else
                viewHolder.check.setVisibility(View.GONE);
            if (data.isCheck()) {
                viewHolder.check.setImageResource(R.drawable.icon_video_selected);
            } else {
                viewHolder.check.setImageResource(R.drawable.icon_video_no_selected);
            }
            List<DownloadedAudioModel.Data> lists = data.getList();
            if (lists != null && lists.size() > 0) {
                Adapter adapter = new Adapter();
                viewHolder.recyclerView.setAdapter(adapter);
                adapter.setData(lists);
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onViewOnClicklistener != null)
                        onViewOnClicklistener.onClick(data);
                }
            });
        }
        return convertView;

    }

    public void setShowCheck(boolean showCheck) {
        isShowCheck = showCheck;
        notifyDataSetChanged();
    }

    public List<DownloadedAudioModel> getList() {
        return pairs;
    }

    public void clear() {
        if (pairs != null) {
            pairs.clear();
            pairs = null;
        }
        media = null;
        if (mediaPlayerUtil != null) {
            mediaPlayerUtil.clearMediaPlayer();
        }
        if (handler != null) {
            handler.sendEmptyMessage(2);
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    private class ViewHolder {
        ImageView img, check;
        TextView name, duty, question;
        RecyclerView recyclerView;
    }

    private Handler handler = new Handler() {
        TextView textView;
        Adapter.ViewHolder holder;
        private boolean stop = false;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (!stop) {
                        sendEmptyMessageDelayed(0, 1000);
                        textView.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        holder.voice_iv.setVisibility(View.GONE);
                        holder.voice_gif.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    holder = (Adapter.ViewHolder) msg.obj;
                    textView = holder.time;
                    stop = false;
                    holder.playLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                    break;
                case 2:
                    if (holder == null || media == null)
                        return;
                    stop = true;
                    holder.voice_iv.setVisibility(View.VISIBLE);
                    holder.voice_gif.setVisibility(View.GONE);
                    holder.playLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    textView.setText(time);
                    playUuid = "";
                    media.seekTo(0);
                    media.pause();
                    media.stop();
                    media.reset();
                    media = null;
                    break;
                case 3:
                    if (media != null) {
                        if (media.isPlaying()) {
                            stop = true;
                            media.pause();
                            holder.voice_iv.setVisibility(View.VISIBLE);
                            holder.voice_gif.setVisibility(View.GONE);
                        } else {
                            stop = false;
                            sendEmptyMessageDelayed(0, 1000);
                            media.start();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void OnError(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnPrepared(MediaPlayer mediaPlayer) {
        //开始播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    public void stopMedia() {
        handler.sendEmptyMessage(2);
    }

    @Override
    public void OnCompletion(MediaPlayer mediaPlayer) {
        handler.sendEmptyMessage(2);
    }

    private class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

        private List<DownloadedAudioModel.Data> list;

        Adapter() {
            list = new ArrayList<>();
        }

        public void setData(List<DownloadedAudioModel.Data> list) {
            this.list.clear();
            this.list.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_downloaded_audio_list, parent, false));
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            final DownloadedAudioModel.Data data = list.get(position);
            if (data != null) {
                holder.time.setText(data.getVoiceTime());
                holder.size.setText(TextUtils.isEmpty(data.getProgressText()) ? "" : data.getProgressText().split("/")[1]);
                if (TextUtils.equals(data.getUuid(), playUuid)) {
                    holder.playLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                } else {
                    holder.playLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                }
                holder.playLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (QuickDoubleClickable.isDoubleClick()) {
                            return;
                        }
                        if (media != null) {
                            if (data.getUuid().equals(playUuid)) {
                                handler.sendEmptyMessage(3);
                            } else {
                                handler.sendEmptyMessage(2);
                            }
                        } else {
                            playUuid = data.getUuid();
                            time = String.valueOf(data.getVoiceTime());
                            Message msg = Message.obtain();
                            msg.what = 1;
                            msg.obj = holder;
                            handler.sendMessage(msg);
                            playAudio(MediaUtil.getAudioFile(CCMediaConfig.DOWNLOAD_DIR, data.getUuid()).getPath());
                        }
                    }
                });
                holder.show_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showText(data.getContent());
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        /**
         * 播放语音
         */
        private void playAudio(String patch) {
            media = mediaPlayerUtil.getLocalMedia(patch);
        }

        /**
         * 查看文字
         */
        public void showText(String content) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
            builder.setMessage(content); //设置内容
            builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private ImageView voice_iv;
            private GifView voice_gif;
            private TextView time, size, show_text;
            private View playLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                playLayout = itemView.findViewById(R.id.play);
                voice_iv = itemView.findViewById(R.id.voice_iv);
                voice_gif = itemView.findViewById(R.id.voice_gif);
                time = itemView.findViewById(R.id.time);
                size = itemView.findViewById(R.id.size);
                show_text = itemView.findViewById(R.id.show_tv);
                show_text.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
                show_text.getPaint().setAntiAlias(true);//抗锯齿
                voice_gif.setGifResource(R.raw.play);
            }
        }

        public void clear() {
            if (this.list != null) {
                this.list.clear();
                this.list = null;
            }
        }
    }

}
